<template>
  <el-dialog
    :before-close="cancelFn"
    v-model="isShowDistributionDialog"
    title="分配角色"
  >
    <el-select
      v-model="roleIdsArr.selectRoleIds"
      :multiple="true"
      filterable
      allow-create
      default-first-option
      :reserve-keyword="false"
      placeholder="请选择"
    >
      <el-option
        v-for="item in roleList"
        :key="item.id"
        :label="item.name"
        :value="item.id"
      />
    </el-select>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancelFn">取消</el-button>
        <el-button type="primary" @click="AdminRoleUpdateFn">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ElMessage, ElMessageBox } from "element-plus";
import { reactive, toRefs, ref, watch, Ref } from "vue";
import {
  getAdminAllRoleListAPI,
  getAdminRoleAPI,
  getAdminRoleUpdateAPI,
} from "../../../request/api";
let props = defineProps<{
  isShowDistributionDialog: boolean;
  adminId: number;
}>();
let emit = defineEmits<{
  (event: "closeDialog", val: boolean, id: number): void;
}>();

let roleList = ref([]) as Ref<getAdminRoleAPIData[]>;

let roleIdsArr = ref<{ selectRoleIds: number[] }>({
  selectRoleIds: [],
});

// 获取指定用户角色列表
const getRole = async (adminId: number) => {
  let res = await getAdminRoleAPI(adminId);
  if (res.code === 200) {
    roleIdsArr.value.selectRoleIds = res.data.map((item) => item.id);
  }
};
//修改用户角色=========
const AdminRoleUpdateFn = async () => {
  ElMessageBox.confirm("此操作将修改当前用户信息, 是否继续?", "Warning", {
    title: "提示",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let res = await getAdminRoleUpdateAPI({
        roleIds: roleIdsArr.value.selectRoleIds.join(","),
        adminId: props.adminId,
      });
      if (res.code !== 200) {
        ElMessage({
          type: "error",
          message: "修改失败",
        });
      } else {
        ElMessage({
          type: "success",
          message: "修改成功",
        });
      }
      cancelFn();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消修改",
      });
      cancelFn();
    });
};
//监听打开弹窗了再发请求获取用户角色
watch(
  () => props.adminId,
  (newVal, oldVal) => {
    if (newVal) {
      //发请求
      getRole(newVal);
    }
  }
);
const cancelFn = () => {
  emit("closeDialog", false, 0);
};

//获取所有角色列表
const getRoleList = async () => {
  let res = await getAdminAllRoleListAPI();
  roleList.value = res.data;
};
getRoleList();
</script>
<style lang="less" scoped>

</style>
